package com.wanshu.sys.service.impl;

import com.wanshu.sys.entity.SysRole;
import com.wanshu.sys.entity.SysUser;
import com.wanshu.sys.service.ISysRoleService;
import com.wanshu.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    //认证校验的方法: 完成帐号的校验
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<SysUser> sysUsers = sysUserService.queryByUsername(username);
        if(sysUsers != null && sysUsers.size() == 1){
            SysUser user = sysUsers.get(0);
            List<SysRole> sysRoles = sysRoleService.queryByUserId(user.getUserId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            if(sysRoles != null && sysRoles.size() > 0){
                for(SysRole item: sysRoles){
                    grantedAuthorities.add(new SimpleGrantedAuthority(item.getRoleName()));
                }
            }
            UserDetails userDetails = new User(user.getUsername(),
                    user.getPassword(), grantedAuthorities);
            return userDetails;
        }
//        if("admin".equals(username)){
//            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//            grantedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
//            //密码模拟数据库查询结果
//            UserDetails userDetails = new User("admin",
//                    "$2a$10$j3C8RGX.5Ik4e0DcFECCBeLGa8hCpYWo4iD1VRVudw1Rqm1gbklkq", grantedAuthorities);
//            return userDetails;
//        }
        return null;
    }

}
